package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private IShopService shopService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryById(Long id) {
        // 从 redis 查询商铺缓存
        String key = CACHE_SHOP_KEY + id;
        String cacheShop = stringRedisTemplate.opsForValue().get(key);
        // 判断是否存在
        if (StrUtil.isNotBlank(cacheShop)) {
            // 不为空，转对象返回
            return Result.ok(JSONUtil.toBean(cacheShop, Shop.class));
        }
        // 不存在从数据库查询0
        Shop shop = shopService.getById(id);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop));
        return Result.ok(shop);
    }

    @Override
    public Object queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1. 判断是否需要根据坐标查询
        if (x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = shopService.query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return page.getRecords();
        }
        // 2. 计算分页参数
        int from = (current - 1) * 5; // 每次查询 5 条
        int end = current * 5;
        // 3. 查询 redis 按照距离排序，分页。
        String key = RedisConstants.SHOP_GEO_KEY + typeId;

        // 为什么 from 没有使用呢，因为不支持分页，需要自己截取
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() // geosearch key bylonlat x y byradius 10 withdistance
                // GeoReference.fromCoordinate() 根据坐标， = bylonlat
                .search(key, GeoReference.fromCoordinate(x, y),
                        // 单位默认是米，5000 = 5公里
                        new Distance(5000),
                        // 携带 withdistance
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance()
                                // 是获取多少条-- end 是每一页的数量。
                                .limit(end));
        if (results == null) {
            return null;
        }

        // 获取结果
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();

        if (list.size() <= from) {
            // 没有下一页，返回空
            return null;
        }

        // 截取数据
        ArrayList<Long> ids = new ArrayList<>(list.size());
        HashMap<String, Distance> distanceMap = new HashMap<>();
        list.stream()
                // 跳过 from 个
                .skip(from).forEach(geoLocationGeoResult -> {
                    // 店铺ID
                    String id = geoLocationGeoResult.getContent().getName();
                    ids.add(Long.valueOf(id));
                    // 获取距离
                    Distance distance = geoLocationGeoResult.getDistance();
                    distanceMap.put(id, distance);
                });
        // 5. 根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shopList = query().in("id", ids).last("order by field(id, " + idStr + ")").list();
        shopList.forEach(shop -> {
            Distance distance = distanceMap.get(shop.getId().toString());
            // 获取距离
            double value = distance.getValue();
            shop.setDistance(value);
        });

        return shopList;
    }
}
